<template>
  <view class="my-publish">
    <!-- Tab切换 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: activeTab === index }"
        @click="handleTabChange(index)"
      >
        {{ tab.name }}
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      @scrolltolower="handleLoadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="handleRefresh"
    >
      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">📦</view>
        <view class="empty-text">暂无订单</view>
      </view>

      <!-- 订单卡片 -->
      <view 
        v-for="order in orderList" 
        :key="order.id"
        class="order-card"
        @click="handleViewDetail(order.id)"
      >
        <!-- 头部 -->
        <view class="order-header">
          <view class="left">
            <text class="icon">{{ getCategoryIcon(order.categoryName) }}</text>
            <text class="name">{{ order.categoryName }}</text>
          </view>
          <view class="status" :style="{ color: getStatusColor(order.status) }">
            {{ getDisplayStatusText(order) }}
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="order-info">
          <view class="info-item">
            <text class="label">订单号:</text>
            <text class="value">{{ order.orderNo }}</text>
          </view>
          <view class="info-item">
            <text class="label">取件:</text>
            <text class="value">{{ order.pickupAddress }}</text>
          </view>
          <view class="info-item">
            <text class="label">送达:</text>
            <text class="value">{{ order.deliveryAddress }}</text>
          </view>
          <view class="info-item">
            <text class="label">费用:</text>
            <text class="value price">¥{{ order.totalAmount || order.actualAmount }}</text>
          </view>
          <view class="info-item" v-if="order.deliveryUserName">
            <text class="label">接单人:</text>
            <text class="value">{{ order.deliveryUserName }}</text>
          </view>
          <view class="info-item">
            <text class="label">时间:</text>
            <text class="value">{{ order.createTime }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions">
          <!-- 待支付 -->
          <template v-if="order.status === 0">
            <button class="btn-secondary" @click.stop="handleCancel(order)">取消订单</button>
            <button class="btn-primary" @click.stop="handlePay(order)">去支付</button>
          </template>

          <!-- 待接单 -->
          <template v-else-if="order.status === 1">
            <button class="btn-secondary" @click.stop="handleCancel(order)">取消订单</button>
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>
          </template>

          <!-- 已送达 -->
          <template v-else-if="order.status === 4">
            <button class="btn-text" @click.stop="handleContact(order)">联系接单人</button>
            <button class="btn-primary" @click.stop="handleConfirm(order)">确认收货</button>
          </template>

          <!-- 其他状态 -->
          <template v-else>
            <button class="btn-text" @click.stop="handleContact(order)" v-if="order.deliveryUserName">
              联系接单人
            </button>
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>
          </template>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">加载中...</view>
      <view v-else-if="!hasMore && orderList.length > 0" class="no-more">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script>
import { getPickupOrderPage, cancelPickupOrder, payPickupOrder, confirmReceive } from '@/api/pickup'
import { getStatusColor as getUnifiedStatusColor } from '@/utils/orderStatus'

export default {
  data() {
    return {
      activeTab: 0,
      tabs: [
        { name: '全部', status: null },
        { name: '待接单', status: 1 },
        { name: '进行中', status: 3 }, // 配送中
        { name: '已完成', status: 6 },
        { name: '已取消', status: 7 }
      ],
      orderList: [],
      loading: false,
      refreshing: false,
      hasMore: true,
      page: {
        current: 1,
        size: 10
      }
    }
  },
  onLoad() {
    this.loadOrderList()
  },
  methods: {
    // 加载订单列表
    async loadOrderList(refresh = false) {
      if (this.loading) return
      
      if (refresh) {
        this.page.current = 1
        this.hasMore = true
        this.orderList = []
      }

      try {
        this.loading = true
        const params = {
          current: this.page.current,
          size: this.page.size,
          role: 'publisher'
        }
        
        // 只有当 status 不为 null 时才添加
        if (this.tabs[this.activeTab].status !== null) {
          params.status = this.tabs[this.activeTab].status
        }
        
        const pageData = await getPickupOrderPage(params)
        
        if (refresh) {
          this.orderList = pageData.records
        } else {
          this.orderList = [...this.orderList, ...pageData.records]
        }
        
        this.hasMore = this.page.current < pageData.pages
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({ title: error.msg || '加载失败', icon: 'none' })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // Tab切换
    handleTabChange(index) {
      this.activeTab = index
      this.loadOrderList(true)
    },

    // 下拉刷新
    handleRefresh() {
      this.refreshing = true
      this.loadOrderList(true)
    },

    // 加载更多
    handleLoadMore() {
      if (this.hasMore && !this.loading) {
        this.page.current++
        this.loadOrderList()
      }
    },

    // 查看详情
    handleViewDetail(orderId) {
      uni.navigateTo({
        url: `/pages/pickup/detail?orderId=${orderId}`
      })
    },

    // 支付订单
    handlePay(order) {
      const amount = order.actualAmount || order.totalAmount || 0
      uni.navigateTo({
        url: `/pages/order/payment?orderId=${order.id}&orderType=2&amount=${amount}`
      })
    },

    // 取消订单
    handleCancel(order) {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '取消中...' })
              await cancelPickupOrder(order.id, '用户取消')
              uni.hideLoading()
              uni.showToast({ title: '订单已取消', icon: 'success' })
              this.loadOrderList(true)
            } catch (error) {
              uni.hideLoading()
              uni.showToast({ title: error.msg || '取消失败', icon: 'none' })
            }
          }
        }
      })
    },

    // 确认收货
    handleConfirm(order) {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到物品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '确认中...' })
              await confirmReceive(order.id)
              uni.hideLoading()
              uni.showToast({ title: '收货成功', icon: 'success' })
              this.loadOrderList(true)
            } catch (error) {
              uni.hideLoading()
              uni.showToast({ title: error.msg || '确认失败', icon: 'none' })
            }
          }
        }
      })
    },

    // 联系接单人
    handleContact(order) {
      if (!order.deliveryUserPhone) {
        uni.showToast({ title: '暂无联系方式', icon: 'none' })
        return
      }
      
      uni.showActionSheet({
        itemList: [`拨打电话: ${order.deliveryUserPhone}`, '复制手机号'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.makePhoneCall({ phoneNumber: order.deliveryUserPhone })
          } else if (res.tapIndex === 1) {
            uni.setClipboardData({ data: order.deliveryUserPhone })
          }
        }
      })
    },

    // 获取分类图标
    getCategoryIcon(categoryName) {
      const iconMap = {
        '取外卖': '🍱',
        '取快递': '📦',
        '取咖啡': '☕',
        '代买': '🛒'
      }
      return iconMap[categoryName] || '📦'
    },

    // 获取显示的状态文本（发布人视角）
    getDisplayStatusText(order) {
      // 对于发布人，待结算(5)应该显示为"已完成"
      if (order.status === 5) {
        return '已完成'
      }
      return order.statusText
    },

    // 获取状态颜色（使用统一的订单状态工具函数）
    getStatusColor(status) {
      // 对于发布人，待结算(5)和已完成(6)都显示为已完成的颜色
      const displayStatus = status === 5 ? 6 : status
      // 代取订单的orderType根据serviceType确定（2-取快递，3-取外卖，4-代取奶咖）
      // 这里统一使用2作为代取订单的基础类型
      return getUnifiedStatusColor(2, displayStatus)
    }
  }
}
</script>

<style scoped>
.my-publish {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
}

.tabs {
  display: flex;
  background: #fff;
  padding: 0 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 28rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #4ECDC4;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background: #4ECDC4;
  border-radius: 3rpx;
}

.order-list {
  flex: 1;
  padding: 24rpx;
}

.empty-state {
  padding: 200rpx 0;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.order-header .left {
  display: flex;
  align-items: center;
}

.order-header .icon {
  font-size: 40rpx;
  margin-right: 12rpx;
}

.order-header .name {
  font-size: 32rpx;
  font-weight: bold;
}

.order-header .status {
  font-size: 28rpx;
  font-weight: bold;
}

.order-info {
  margin-bottom: 24rpx;
}

.info-item {
  display: flex;
  margin-bottom: 16rpx;
  font-size: 26rpx;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  color: #999;
  min-width: 100rpx;
}

.info-item .value {
  flex: 1;
  color: #333;
}

.info-item .price {
  color: #FF6B6B;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
}

.order-actions button {
  padding: 16rpx 32rpx;
  font-size: 26rpx;
  border-radius: 8rpx;
  border: none;
}

.btn-primary {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
}

.btn-secondary {
  background: #F5F5F5;
  color: #666;
}

.btn-text {
  background: transparent;
  color: #4ECDC4;
  border: 1rpx solid #4ECDC4 !important;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: #999;
}
</style>

